//
//  ViewController.swift
//  1.16.Accepting User Text Input with UITextField
//
//  Created by joker on 15/7/22.
//  Copyright (c) 2015年 joker. All rights reserved.
//

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    var textField: UITextField!
    var label: UILabel!
    
    func calculateAndDisplayTextFieldLengthWithText(text: String) {
        var characterOrCharacters = "Character"
        if count(text) != 1 {
            characterOrCharacters += "s"
        }
        
        let stringLength = count(text)
        
        label.text = "\(stringLength) \(characterOrCharacters)"
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        /* #1 */
//        textField = UITextField(frame: CGRect(x: 0, y: 0, width: 200, height: 31))
//        
//        textField.borderStyle = .RoundedRect
//        
//        textField.contentVerticalAlignment = .Center
//        
//        textField.textAlignment = .Center
//        
//        textField.text = "Sir Richard Branson"
//        
//        textField.center = view.center
//
//        
//        view.addSubview(textField)
        /* #2 */
        textField = UITextField(frame: CGRect(x: 38, y: 30, width: 220, height: 32))
        
        textField.delegate = self
        
        textField.borderStyle = .RoundedRect
        
        textField.contentVerticalAlignment = .Center
        
        textField.textAlignment = .Center
        
//        textField.text = "Sir Richard Branson"
        textField.placeholder = "Enter your text here ..."
        
        let currencyLabel = UILabel(frame: CGRectZero)
        currencyLabel.text = NSNumberFormatter().currencySymbol
        currencyLabel.font = textField.font
        currencyLabel.textAlignment = .Right
        currencyLabel.sizeToFit()
        currencyLabel.frame.size.width += 10
        textField.leftView = currencyLabel
        textField.leftViewMode = .Always
        view.addSubview(textField)
        
        label = UILabel(frame: CGRect(x: 38, y: 61, width: 220, height: 31))
        view.addSubview(label)
        calculateAndDisplayTextFieldLengthWithText(textField.text)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    //MARK: UITextFieldDelegate
    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        let text = textField.text as NSString
        
        let wholeText = text.stringByReplacingCharactersInRange(range, withString: string)
        calculateAndDisplayTextFieldLengthWithText(wholeText)
        return true
    }
    
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
}

